<?php

namespace app\controllers;

use dektrium\user\models\Profile;
use Yii;
use app\models\MsgSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\Upfile;

use app\api\Constant;
use app\models\GkyMsgUser;
use app\models\GkyQyhUser;
use app\models\Msg;
use app\models\GkyQyh;
use app\common\utils\QyWechat;

/**
 * MsgController implements the CRUD actions for Msg model.
 */
class MsgController extends Controller
{
     public $layout='main_1';
    public function behaviors()
    {
        return [
            'access' => [
                'class' => \yii\filters\AccessControl::className(),
                'rules' => [
                    [ 'allow' => true,'roles' => ['@'],],
                ],
            ],
            
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Msg models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new MsgSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Msg model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Msg model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Msg();

        if ($model->load(Yii::$app->request->post())) {

            $userProfile = Profile::findOne(Yii::$app->user->id);

            $model->addmanid = $userProfile->qyh_user_id;

            $model->save();
            
            //得到从页面post过来的发送对象
            $request = \Yii::$app->request;
            $user = $request->post('selects2');
            $data = explode(',', $user);
     
            $msg = Msg::find()->where(['title'=>$model->title])->orderBy(['id'=>SORT_DESC])->one();
            $accepters = isset($data) ? $data : [];
            for($i = 0; $i < count($accepters);$i++){
                $msgUser = new GkyMsgUser();
                $msgUser->msgid = $msg->id;
                $msgUser->userid = $accepters[$i];
                $msgUser->save();
            }
            //发送消息
            $this->sendMessage($accepters,$msg);
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Msg model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }
    
    //删除附件
    public function actionClose(){
        $fileid=  Yii::$app->request->post('fileid');
        $upfile=  Upfile::findOne(["id"=>$fileid]);
        $res="";
        if($upfile->delete()){
            $res=1;
        }else{
            $res=0;
        }
        echo json_encode(array('res'=>$res));
    }

    /**
     * Deletes an existing Msg model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Msg model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Msg the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Msg::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
     public function sendMessage($accepters,$msg){

        $touser = GkyQyhUser::findUseridByList($accepters,Constant::$GKY_CORPID);
        $touser = implode("|",$touser);
        if($msg->msgtype == 'OA办文'){
            $picUrl = \Yii::$app->request->hostInfo.'/GkyWechat/images/oa.png';
        }else{
            $picUrl = \Yii::$app->request->hostInfo.'/GkyWechat/images/meeting.jpg';
        }

        $message = [
            "touser" => $touser,
//            "toparty" => "PartyID1|PartyID2 ",
//            "totag" => "TagID1|TagID2 ",
            "safe"=> "0",			//是否为保密消息，对于news无效
            "agentid" => "1",	//应用id
            "msgtype" => "news",  //根据信息类型，选择下面对应的信息结构体

            "news" => array(			//不支持保密
                  "articles" => array(    //articles  图文消息，一个图文消息支持1到10个图文
                      array(
                          "title" => $msg->title,             //标题
                          "description" => $msg->description, //描述
                          "url" => "http://gky.fukangyun.com/GkyWechat/message/content.html?msgid=".$msg->id,                 //点击后跳转的链接。可根据url里面带的code参数校验员工的真实身份。
                          "picurl" => $picUrl,          //图文消息的图片链接,支持JPG、PNG格式，较好的效果为大图640*320，
                                                          //小图80*80。如不填，在客户端不显示图片
                      ),
                  )
              ),
        ];

        $this->send($message);

    }
    
    
     public function send($message){
        //获取当前企业号
        $weaccount = GkyQyh::findByCorpid(Constant::$GKY_CORPID);

        $options = array(
            'token'=>'gky',   //填写应用接口的Token
            'encodingaeskey'=>$weaccount->aeskey,//填写加密用的EncodingAESKey
            'appid'=>$weaccount->corpid,  //填写高级调用功能的appid
            'appsecret'=>$weaccount->secret, //填写高级调用功能的密钥
        );
        $weObj = new QyWechat($options);
        $weObj->sendMessage($message);
    }
    
}
